package packagecmdimp;

import java.util.regex.Pattern;

import package1.OrderConsole;
import package2.OrderApplication;
import package2.OrderDao;
import packageCommand.SystemCommand;
import packagerole.User;

public class UserSignupCommand extends SystemCommand {

	@Override
	public void execute() {
		OrderDao dao = new OrderDao();

		String username = OrderConsole.askUserInput("请输入用户名");
		// check username
		while (dao.isUsernameExists(username)) {
			OrderConsole.println("用户名已存在！");
			username = OrderConsole.askUserInput("请输入用户名");
		}

		String password = null;
		while (true) {
			password = OrderConsole.askUserInput("请输入密码");
			try {
				// validate password
				validatePassword(password);
				break;
			} catch (Exception e) {
				OrderConsole.println("密码格式不对！" + e.getMessage());
				continue;
			}
		}

		String nickname = OrderConsole.askUserInput("请输入昵称");

		User user = dao.userSignup(username, password, nickname);
		OrderApplication.getInstance().setPlayerProfile(user);
		
		OrderConsole.println("恭喜你，注册用户成功！");
		
	}

	private void validatePassword(String password) throws Exception {
		// 1. length >= 6
		Pattern lenPattern = Pattern.compile("[0-9a-zA-Z]{6,}");
		if (!lenPattern.matcher(password).find()) {
			throw new Exception("密码长度必需大于等于6位");
		}

		// 2. not all number
		Pattern numPattern = Pattern.compile("[0-9]");
		if (!numPattern.matcher(password).find()) {
			throw new Exception("密码至少需要含有一位数字");
		}

		// 3. not all word
		Pattern wordPattern = Pattern.compile("[a-zA-Z]");
		if (!wordPattern.matcher(password).find()) {
			throw new Exception("密码至少需要含有一位字母");
		}
	}
}
